/**
 * 
 */
package com.wandar.gc.handler;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.wandar.gc.config.TypeEnum;
import com.wandar.gc.schema.PropertySchema;

/**
 * @author huangxiaoming
 *
 */
public class ConfigHandler {
	
	/**
	 * 根据表结构获取属性详情
	 * huangxiaoming
	 * 2014年11月29日下午6:39:46
	 * @param connection
	 * @param databaseName
	 * @param tableName
	 * @return
	 * @throws SQLException
	 */
	public static List<PropertySchema> getPropertySchema(Connection connection,String databaseName,String tableName) throws SQLException{
		
		List<PropertySchema> propertySchemas = new ArrayList<PropertySchema>();
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT ");
		sql.append("  	b.column_name,");
		sql.append("  	UCASE(b.column_type) AS column_type,");
		sql.append("  	UCASE(b.data_type) AS data_type,");
		sql.append("  	b.column_comment ,");
		sql.append("  	(SELECT  'PRI' FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE a WHERE a.TABLE_SCHEMA = ? AND a.TABLE_NAME = ? AND a.COLUMN_NAME = b.column_name) prikey ");
		sql.append(" FROM");
		sql.append("  	information_schema.COLUMNS b ");
		sql.append(" WHERE TABLE_SCHEMA = ? ");
		sql.append(" AND TABLE_NAME = ? ");
		
		PreparedStatement preparedStatement = connection.prepareStatement(sql.toString());
		preparedStatement.setString(1, databaseName);
		preparedStatement.setString(2, tableName);
		preparedStatement.setString(3, databaseName);
		preparedStatement.setString(4, tableName);
		ResultSet resultSet = preparedStatement.executeQuery();

		while (resultSet.next()) {
			//获取表结构字段类型
			PropertySchema propertySchema = new PropertySchema();
			propertySchema.setColumnComment(resultSet.getString("column_comment"));
			propertySchema.setColumnType(resultSet.getString("column_type"));
			propertySchema.setDataType(resultSet.getString("data_type").toUpperCase());
			propertySchema.setColumnName(resultSet.getString("column_name"));
			propertySchema.setPrikey(resultSet.getString("prikey"));  
			
			
			//根据数据库类型获取属性类型
			String pk_dataType = propertySchema.getDataType();
			TypeEnum typeEnum = TypeEnum.getBySqlType(pk_dataType);
			propertySchema.setPropertyType(typeEnum.getType());
			propertySchema.setPackageTarget(typeEnum.getJavaType());
			propertySchema.setJdbcType(typeEnum.getJdbcType());
			
			//根据数据库字段获取生成方法名称 和字段名称
			
			
			propertySchemas.add(propertySchema);
		}
		
		return propertySchemas;
	}

}
